package com.jtpay.ysfproductionprocess.ui.activity;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.*;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.jtpay.ysfproductionprocess.R;
import com.jtpay.ysfproductionprocess.enums.LogLevelEnum;
import com.jtpay.ysfproductionprocess.enums.LogModuleEnum;
import com.jtpay.ysfproductionprocess.frida.FridaHelper;
import com.jtpay.ysfproductionprocess.http.ApiHelper;
import com.jtpay.ysfproductionprocess.http.listener.TransApiResultListener;
import com.jtpay.ysfproductionprocess.model.CryptModel;
import com.jtpay.ysfproductionprocess.model.HeaderModel;
import com.jtpay.ysfproductionprocess.model.RemoteTaskModel;
import com.jtpay.ysfproductionprocess.provider.UnionPayEncryptProvider;
import com.jtpay.ysfproductionprocess.utils.*;
import com.jtpay.ysfproductionprocess.utils.manager.ToastUtil;
import com.jtpay.ysfproductionprocess.ysf.YsfLaunch;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import static com.jtpay.ysfproductionprocess.http.ApiHelper.ApiStatusEnum.GET_TASK_API;
import static com.jtpay.ysfproductionprocess.provider.UnionPayEncryptProvider.deleteDb;
import static com.jtpay.ysfproductionprocess.utils.ActivityHelper.openUnionPayService;
import static com.jtpay.ysfproductionprocess.utils.ActivityHelper.startUnionPayMainActivity;
import static com.jtpay.ysfproductionprocess.utils.PayContext.*;
import static com.jtpay.ysfproductionprocess.utils.PayFileUtil.*;

/**
 * MainActivity
 */
public class MainActivity extends BaseActivity {

    private YsfLaunch mYsfLaunch;
    private Handler mHandler;
    //支付回调结果广播
    private GetHeaderReceiver mReceiver;
    private CryptModel mCryptModel;
    private RemoteTaskModel mRemoteTaskModel;

    private int logCount = 0;//log lines count
    private Timer timer = new Timer();
    private boolean isAppFirstStart = false;

    private Menu menu;
    private TextView mLogContent;
    private MainTimerTask timerTask;
    private EditText et_shop_code;
    private EditText et_shop_ysf_account;
    private Button btn_set_account_info;
    private Button btn_offline_alarm;

    @Override
    protected void onResume() {
        super.onResume();
        openAccessibilityServiceSettingIfNeed();
    }

    @Override
    protected void onDestroy() {
        showLog("MainActivity onDestroy");
        //注销广播
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_main;
    }

    /**
     * init View
     */
    @Override
    protected void initView() {
        mLogContent = findViewById(R.id.LogContent);
        mLogContent.setMovementMethod(ScrollingMovementMethod.getInstance());
        et_shop_code = findViewById(R.id.et_product_shop_code);
        et_shop_ysf_account = findViewById(R.id.et_product_account_code);
        btn_set_account_info = findViewById(R.id.btn_set_account);
        btn_offline_alarm = findViewById(R.id.btn_offline_alarm);
        et_shop_code.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                MenuItem toolItem = menu.findItem(R.id.menu_tool);
                toolItem.setVisible(true);
                return true;
            }
        });
        et_shop_ysf_account.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                MenuItem toolItem = menu.findItem(R.id.menu_tool);
                toolItem.setVisible(false);
                return true;
            }
        });

    }

    /**
     * init Data
     */
    @Override
    protected void initData() {
        mHandler = new Handler();
        doRequestPermissions();
        //广播注册等
        mReceiver = new GetHeaderReceiver();
        IntentFilter intentFilter = new IntentFilter(ACTION_UNION_PAY_GET_HEADER);
        intentFilter.addAction(ACTION_UNION_PAY_GET_HEADER_RESULT);
        intentFilter.addAction(ACTION_CONTINUE_TASK);
        intentFilter.addAction(ACTION_UNION_PAY_CHECK_ACCOUNT);
        intentFilter.addAction(ACTION_UNION_PAY_SHOW_LOG);
        intentFilter.addAction(ACTION_UNION_PAY_SHOW_TOAST);
        LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, intentFilter);

        et_shop_code.setText(sharedPreferenceUtil.SP_READ(this, SP_SHOP_CODE_KEY));
        et_shop_ysf_account.setText(sharedPreferenceUtil.SP_READ(this, SP_SHOP_YSF_ACCOUNT_KEY));

        ApiConstant.URL_IP = sharedPreferenceUtil.SP_READ(this, SP_API_BASE_IP_KEY);

        AlarmSoundManager.getInstance().setChangedListener(new AlarmSoundManager.AlarmStatusChangedListener() {
            @Override
            public void alarmStatus(boolean isPlaying) {
                if (isPlaying) {
                    setViewVisibility(btn_offline_alarm, View.VISIBLE);
                } else {
                    setViewVisibility(btn_offline_alarm, View.GONE);
                }
            }
        });
        isAppFirstStart = true;
//        FridaHelper.startFridaServer(getHandler());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        this.menu = menu;
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_log_clean:
                mLogContent.setText(getString(R.string.log_content_def));
                break;
            case R.id.menu_start_frida_server:
                FridaHelper.startFridaServer();
                break;
            case R.id.menu_start_service:
                openAccessibilityServiceSettingIfNeed();
                break;
            case R.id.menu_verify_account:
                CheckAccountStatus = 1;
                startUnionPayMainActivity();
                break;
            case R.id.menu_delete_db:
                deleteDb(this);
                break;
            case R.id.menu_set_account_info:
                setFocusable(et_shop_code, true);
                setFocusable(et_shop_ysf_account, true);
                setViewVisibility(btn_set_account_info, View.VISIBLE);
                break;
            case R.id.menu_push_log:
                pushLog();
                break;
            case R.id.exit:
                LogUtil.logUpload(MainActivity.this, getString(R.string.exit), LogModuleEnum.EXIT.message, LogLevelEnum.LOG_INFO.message);
                android.os.Process.killProcess(android.os.Process.myPid());
                break;
            case R.id.menu_start_task:
                getServerTask();
                break;
            case R.id.menu_start_alarm:
                AlarmSoundManager.getInstance().play();
                break;
            case R.id.menu_alarm_set:
                startAlarmSettingUI();
                break;
            case R.id.openAccessService:
                openAccessibilityServiceSetting();
                break;
            case R.id.openProgramSetting:
                openProgramSetting();
                break;
            case R.id.menu_start_ysf:
                startYsf();
                break;
            default:
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * @param view target view
     */
    public void setAccountInfo(View view) {
        String shopCode = et_shop_code.getText().toString();
        String ysfAccount = et_shop_ysf_account.getText().toString();
        if (TextUtils.isEmpty(shopCode) || TextUtils.isEmpty(ysfAccount)) {
            showLog(getString(R.string.et_info_null_tips));
            return;
        }
        getServerAddress(shopCode, ysfAccount);
    }

    /**
     * @param view target view
     */
    public void startTask(View view) {
        NotificationManager notificationManager =
                (NotificationManager) AppApplication.getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            showLog("NotificationManager null!");
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
                && !notificationManager.isNotificationPolicyAccessGranted()) {
            showLog(getString(R.string.notification_policy_access_tips));
            Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
            AppApplication.getContext().startActivity(intent);
            return;
        }
        String baseIp = sharedPreferenceUtil.SP_READ(this, SP_API_BASE_IP_KEY);
        if (TextUtils.isEmpty(baseIp) || "null".equals(baseIp)) {
            showLog(getString(R.string.server_address_error));
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.alert)
                .setMessage(R.string.product_alert_message)
                .setPositiveButton(R.string.submit, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        showLog(getString(R.string.in_production));
                        getApiHelper().setStatusEnum(GET_TASK_API);
                        CheckAccountStatus = 1;
                        PayContext.resetErrorCount();
                        restartUnionPay();
                    }
                })
                .create()
                .show();

//        getServerTask();
    }

    /**
     * @param view target view stopAlarm
     */
    public void stopAlarm(View view) {
        AlarmSoundManager.getInstance().stop();
    }

    @Override
    protected void getServerAddress(final String shopCode, final String ysfAccount) {
        if (TextUtils.isEmpty(shopCode) || TextUtils.isEmpty(ysfAccount)) {
            return;
        }
        getApiHelper().getServerAPI(shopCode, ysfAccount, new TransApiResultListener<String>() {
            @Override
            public void trans(String data) {
                if (TextUtils.isEmpty(data)) {
                    showLog(String.format("%s data null", getString(R.string.set_account_info)));
                    return;
                }
                sharedPreferenceUtil.SP_SAVE(
                        MainActivity.this, SP_SHOP_CODE_KEY, shopCode);
                sharedPreferenceUtil.SP_SAVE(
                        MainActivity.this, SP_SHOP_YSF_ACCOUNT_KEY, ysfAccount);
                sharedPreferenceUtil.SP_SAVE(
                        MainActivity.this, SP_API_BASE_IP_KEY, data);
                setFocusable(et_shop_code, false);
                setFocusable(et_shop_ysf_account, false);
                setViewVisibility(btn_set_account_info, View.GONE);
                showLog(String.format("%s success", getString(R.string.set_account_info)));
            }
        });
    }

    @Override
    protected void getServerTask() {
        showLog("cycle request new server's task");
        getApiHelper().getTaskAPI(new TransApiResultListener<RemoteTaskModel>() {
            @Override
            public void trans(RemoteTaskModel model) {
                mRemoteTaskModel = model;
                switch (CheckAccountStatus) {
                    case 0:
                        checkAccountOkAndRunNext();
                        break;
                    case 1:
                        startUnionPayMainActivity();
                        break;
                    default:
                }
            }
        });
    }

    private void checkAccountOkAndRunNext() {
        if (mRemoteTaskModel == null) {
            getServerTask();
            return;
        }
        int type = mRemoteTaskModel.getTaskType();
        showLog("startTask type = " + type);
        switch (mRemoteTaskModel.getTaskType()) {
            case 3:
                //解密云闪付查单返回任务
                mCryptModel = new CryptModel();
                mCryptModel.setMoney(mRemoteTaskModel.getMoney());
                mCryptModel.setRemark(mRemoteTaskModel.getReason());
                mCryptModel.setOrderId(mRemoteTaskModel.getUnionPayOrderId());
                mCryptModel.setEn_content(mRemoteTaskModel.getEn_content());
                getApiHelper().setStatusEnum(ApiHelper.ApiStatusEnum.SET_DECRYPT_CONTENT);
                resumeGetDecryptInfoCycle(mCryptModel, mRemoteTaskModel.getDbType());
                break;
            case 1:
                // 生产任务，加密Header
                getApiHelper().setStatusEnum(ApiHelper.ApiStatusEnum.EN_QR_INFO);
                resumeGetEncryptInfoCycle(mRemoteTaskModel);
                break;
            case 998:
                String time = mRemoteTaskModel.getTime();
                LogUtil.log("998开始" + time);
                uploadLogFile(time);
                break;
            case 2:
                // 加密OrderId，返回OrderId和Header信息
                getApiHelper().setStatusEnum(ApiHelper.ApiStatusEnum.EN_ORDER_ID);
                resumeGetEncryptInfoCycle(mRemoteTaskModel);
                break;
        }
    }

    public void uploadLogFile(String time) {
        String id = et_shop_ysf_account.getText().toString();
        if (TextUtils.isEmpty(id)) {
            showToast(getString(R.string.no_account_is_currently_logged_in));
            return;
        }
        String fileName = FILE_LOG_FIRST_NAME + time + FILE_PREFIX;
        String filePath = getTargetLogFileDirPath() + File.separator + fileName;
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        if (time.equals(getNowDate())) {
            String newFileName = TEMP_FILE_LOG_FIRST_NAME + time + FILE_PREFIX;
            String newFilePath = getTargetLogFileDirPath() + File.separator + newFileName;
            if (copyFile(filePath, newFilePath)) {
                String subTempPath = newFilePath.substring(newFilePath.length() - 14, newFilePath.length());
                getApiHelper().fileUploadAPI(id, PAYMENT, newFilePath, subTempPath, new TransApiResultListener<String>() {
                    @Override
                    public void trans(String path) {
                        getServerTask();
                        deleteAlreadyUploadFile(path);
                    }
                });
                return;
            }
        }
        getApiHelper().fileUploadAPI(id, PAYMENT, filePath, time + FILE_PREFIX, new TransApiResultListener<String>() {
            @Override
            public void trans(String path) {
                getServerTask();
                deleteAlreadyUploadFile(path);
            }
        });
    }

    /**
     * reset Status And Get Encrypt Info Cycle
     *
     * @param remoteTaskModel RemoteTaskModel
     */
    private void resumeGetEncryptInfoCycle(RemoteTaskModel remoteTaskModel) {
        if (remoteTaskModel == null) {
            getServerTask();
            return;
        }
        UnionPayEncryptProvider.insertEncryptInfo(MainActivity.this, remoteTaskModel);
        getEncryptInfoCycle(remoteTaskModel.getReason(),
                remoteTaskModel.getDbType(), NEED_QR_PRODUCT_COUNT_DEF);
    }

    /**
     * get Encrypt Info Cycle to do next step
     *
     * @param reason qrCode remark
     * @param type   encrypt db type
     */
    private void getEncryptInfoCycle(final String reason, final int type, int count) {
        mCryptModel = UnionPayEncryptProvider.selectEncryptInfo(
                MainActivity.this, reason, type);
        if (count < 1) {
            restartUnionPay();
            return;
        }
        if (mCryptModel == null || mCryptModel.getEn_cryptModel() == null) {
            final int index = count - 1;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getEncryptInfoCycle(reason, type, index);
                }
            }, QR_PRODUCT_DELAY_TIME_DEF);
            return;
        }
        HeaderModel headerModel = readHeaderModelData();
        mCryptModel.setEn_headerModel(headerModel);
        if (mCryptModel.getEn_headerModel() == null) {
            startYsfMainActivityAndResetClickNum();
        } else if (TextUtils.isEmpty(mCryptModel.getEn_orderId())) { // 生产获取Header和加密等信息
            getApiHelper().getEncryptQrInfoAPI(mCryptModel, new TransApiResultListener<CryptModel>() {
                @Override
                public void trans(CryptModel model) {
                    //解密二维码信息
                    mCryptModel = model;
                    resumeGetDecryptInfoCycle(mCryptModel, 0);
                }
            });
        } else {
            getApiHelper().setOrderIdAPI(mCryptModel, new TransApiResultListener<String>() {
                @Override
                public void trans(String data) {
                    getServerTask();
                }
            });
        }
    }

    private HeaderModel readHeaderModelData() {
        String headerStr = PayFileUtil.ReadTxtFile(HEADER_DATE_PATH);
        LogUtil.log("readHeaderModelData headerStr : " + headerStr);
        HeaderModel headerModel;
        try {
            headerModel = gson.fromJson(headerStr, HeaderModel.class);
            LogUtil.log("readHeaderModelData headerModel : " + headerModel.toString());
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.log("readHeaderModelData : " + e.getMessage());
            headerModel = null;
        }
        return headerModel;
    }

    /**
     * @param encryptModel EncryptModel
     */
    private void resumeGetDecryptInfoCycle(CryptModel encryptModel, int type) {
        if (encryptModel == null) {
            getServerTask();
            return;
        }
        UnionPayEncryptProvider.insertDecryptInfo(
                MainActivity.this, encryptModel, type);
        getDecryptInfoCycle(encryptModel.getRemark(), type, NEED_QR_PRODUCT_COUNT_DEF);
    }

    /**
     * @param reason qr reason
     */
    private void getDecryptInfoCycle(final String reason, final int type, int cycleCount) {
        CryptModel cryptModel = UnionPayEncryptProvider.selectDecryptInfo(
                MainActivity.this, reason, type);
        if (cycleCount < 1) {
            restartUnionPay();
            return;
        }
        if (cryptModel == null) {
            final int count = cycleCount - 1;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    getDecryptInfoCycle(reason, type, count);
                }
            }, QR_PRODUCT_DELAY_TIME_DEF);
        } else if (mRemoteTaskModel != null && mRemoteTaskModel.getTaskType() == 3) {
            cryptModel.setOrderId(mRemoteTaskModel.getUnionPayOrderId());
            cryptModel.setEn_content(mRemoteTaskModel.getEn_content());
            getApiHelper().setDecryptContentAPI(cryptModel, new TransApiResultListener<String>() {
                @Override
                public void trans(String data) {
                    //wait for new task
                    getServerTask();
                }
            });
        } else {
            getApiHelper().storageQrInfoAPI(cryptModel, new TransApiResultListener<String>() {
                @Override
                public void trans(String data) {
                    //wait for new task
                    getServerTask();
                }
            });
        }
    }

    @Override
    public void finish() {
//        super.finish();
        moveTaskToBack(true);
    }

    /**
     * open AccessibilityService Setting if needed
     */
    private void openAccessibilityServiceSettingIfNeed() {
        if (isAccessibilitySettingsOn(this)) {
//            showLog(getString(R.string.service_already_opened_tips));
            return;
        }
        openUnionPayService();
        //查询是否服务开启成功
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isAccessibilitySettingsOn(MainActivity.this)) {
                    showToast(getString(R.string.service_auto_open_fail_tips));
                } else {
                    showLog(getString(R.string.service_already_opened_tips));
                    if (!isAppFirstStart) {
                        CheckAccountStatus = 1;
                        startYsf();
                    }
                }
            }
        }, QR_PRODUCT_DELAY_TIME_DEF);
    }

    public void pushLog() {
        String id = et_shop_ysf_account.getText().toString();
        if (TextUtils.isEmpty(id)) {
            showToast(getString(R.string.no_account_is_currently_logged_in));
            return;
        }
        String filePath = getTargetLogFileDirPath();
        File fileAll = new File(filePath);
        if (!fileAll.exists() || !fileAll.isDirectory() || fileAll.listFiles() == null) {
            return;
        }
        for (File file : fileAll.listFiles()) {
            if (!file.isFile() || file.getPath().contains(getNowDate())) {
                continue;
            }
            String path = file.getAbsolutePath();
            String subPath = path.substring(path.length() - 14, path.length());
            getApiHelper().fileUploadAPI(id, PAYMENT, file.getAbsolutePath(), subPath, new TransApiResultListener<String>() {
                @Override
                public void trans(String data) {
                    getServerTask();
                    deleteAlreadyUploadFile(data);
                }
            });
        }
        String oldPath = getTargetLogFileDirPath() + File.separator + getCurLogFileName();
        String newPath = getTargetLogFileDirPath() + File.separator + gettempCurLogFileName();
        if (copyFile(oldPath, newPath)) {
            String subTempPath = newPath.substring(newPath.length() - 14, newPath.length());
            getApiHelper().fileUploadAPI(id, PAYMENT, newPath, subTempPath, new TransApiResultListener<String>() {
                @Override
                public void trans(String path) {
                    getServerTask();
                    deleteAlreadyUploadFile(path);
                }
            });
        }
    }

    public void deleteAlreadyUploadFile(String path) {
        File file = new File(path);
        file.delete();
        String filePath = getTargetLogFileDirPath();
        File fileAll = new File(filePath);
        if (!fileAll.exists() || !fileAll.isDirectory() || fileAll.listFiles() == null) {
            return;
        }
        for (File oldfile : fileAll.listFiles()) {
            if (!oldfile.isFile() || oldfile.getPath().contains(getCurLogFileName())) {
                ToastUtil.showShort(this.getString(R.string.log_upload_success));
            }
        }
    }

    //支付回调(广播通知)实现部分
    private class GetHeaderReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getAction() == null) {
                LogUtil.log("onReceive BroadcastReceiver data error ");
                return;
            }
            LogUtil.log("onReceive BroadcastReceiver : " + intent.getAction());
            switch (intent.getAction()) {
                case ACTION_UNION_PAY_GET_HEADER:
                    if (timerTask != null) {
                        timerTask.cancel();
                    }
                    showLog("need get new header");
                    startYsfMainActivityAndResetClickNum();
                    break;
                case ACTION_UNION_PAY_CHECK_ACCOUNT:
                    String account = intent.getStringExtra(BROADCAST_ACCOUNT_KEY);
                    LogUtil.log("云闪付账号为:" + account);
                    String programAccount = sharedPreferenceUtil.SP_READ(
                            MainActivity.this, SP_SHOP_YSF_ACCOUNT_KEY);
                    if (programAccount.equals(account)) {
                        showLog(getString(R.string.account_verify_success));
                        LogUtil.logUpload(MainActivity.this, getString(R.string.account_verify_success), LogModuleEnum.ACCOUNT_VERIFY.message, LogLevelEnum.LOG_INFO.message);
                    } else {
                        showLog(getString(R.string.account_verify_error));
                        LogUtil.logUpload(MainActivity.this, getString(R.string.account_verify_error), LogModuleEnum.ACCOUNT_VERIFY.message, LogLevelEnum.LOG_ERROR.message);
                        if (timerTask != null) {
                            timerTask.cancel();
                        }
                        break;
                    }
                    if (!getApiHelper().getStatusEnum().equals(GET_TASK_API)) {
                        checkAccountOkAndRunNext();
                    }
                    break;
                case ACTION_CONTINUE_TASK:
                    getServerTask();
                    break;
                case ACTION_UNION_PAY_SHOW_LOG:
                    String content = String.valueOf(intent.getStringExtra(BROADCAST_CONTENT_KEY));
                    if (!TextUtils.isEmpty(content)) {
                        showLog(content);
                    }
                    break;
                case ACTION_UNION_PAY_SHOW_TOAST:
                    content = String.valueOf(intent.getStringExtra(BROADCAST_CONTENT_KEY));
                    if (!TextUtils.isEmpty(content)) {
                        showToast(content);
                    }
                    break;
                case ACTION_UNION_PAY_GET_HEADER_RESULT:
                    if (timerTask != null) {
                        timerTask.cancel();
                    }
                    LogUtil.log("ACTION_UNION_PAY_GET_HEADER_RESULT api status : "
                            + getApiHelper().getStatusEnum().name());
                    switch (getApiHelper().getStatusEnum()) {
                        case EN_QR_INFO:
                        case STORAGE_QR_INFO:
                            dealErrorProductTask();
                            break;
                        default:
                            getServerTask();
                            break;
                    }
                    break;
                default:
            }
        }
    }

    private void startYsf() {
        if (null == mYsfLaunch) {
            mYsfLaunch = new YsfLaunch();
        }
        needSendBroadcast = true;
        isAppFirstStart = false;
        if (timerTask != null) {
            timerTask.cancel();
        }
        timerTask = new MainTimerTask();
        timer.schedule(timerTask, QR_PRODUCT_GET_HEADER_DELAY_TIME);
        mYsfLaunch.startYsfActivity();
    }

    /**
     * start Ysf MainActivity And Reset Click Num
     */
    private void startYsfMainActivityAndResetClickNum() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        timerTask = new MainTimerTask();
        timer.schedule(timerTask, QR_PRODUCT_GET_HEADER_DELAY_TIME);
        resetProductCount();
        showLog("startYsfMainActivity");
        ActivityHelper.startUnionPayMainActivity();
    }

    /**
     * restartUnionPay
     */
    private void restartUnionPay() {
        showLog("restart unionPay");
        if (PayContext.API_ERROR_COUNT < 0) {
            LogUtil.log(getString(R.string.ysf_restart_error));
            AlarmSoundManager.getInstance().play();
            return;
        }
        PayContext.API_ERROR_COUNT -= 1;
        deleteDb(this);
        ActivityHelper.stopUnionPay();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startYsf();
            }
        }, 1500);
    }

    /**
     * @param content String
     */
    @Override
    protected void showLog(final String content) {
        LogUtil.log(content);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                logCount++;
                if (logCount == LOG_CLEAN_LINE) {
                    mLogContent.setText(String.format("%s\n", getString(R.string.log_content_def)));
                    mLogContent.requestFocus();
                    mLogContent.scrollTo(0, 0);
                    logCount = 0;
                }
                mLogContent.append(content + "\n");
                int offset = mLogContent.getLineCount() * mLogContent.getLineHeight();
                if (offset > mLogContent.getHeight()) {
                    mLogContent.scrollTo(0, offset - mLogContent.getHeight());
                }
            }
        });
    }

    @Override
    protected void showToast(String content) {
        showLog(content);
        ToastUtil.showShort(content);
    }

    private void setFocusable(View view, boolean clickable) {
        view.setFocusable(clickable);
        view.setFocusableInTouchMode(clickable);
    }

    /**
     * timerTask getHeader
     */
    class MainTimerTask extends TimerTask {
        @Override
        public void run() {
            if (CheckAccountStatus == 0) {
                restartUnionPay();
            } else {
                ActivityHelper.stopUnionPay();
                showLog(getString(R.string.account_status_error));
                AlarmSoundManager.getInstance().play();
            }
            if (timerTask != null) {
                timerTask.cancel();
            }
        }
    }

    private void dealErrorProductTask() {
        if (mRemoteTaskModel == null) {
            showLog("dealErrorProductTask mRemoteTaskModel"
                    + getString(R.string.data_error));
            getServerTask();
            return;
        }
        CryptModel cryptModel = new CryptModel();
        cryptModel.setMoney(mRemoteTaskModel.getMoney());
        cryptModel.setRemark(mRemoteTaskModel.getReason());
        cryptModel.setDe_qr_content("error");
        getApiHelper().storageQrInfoAPI(cryptModel, new TransApiResultListener<String>() {
            @Override
            public void trans(String data) {
                //wait for new task
                getServerTask();
            }
        });

    }
}


